package org.fast.cms.service.admin.impl;

import java.util.List;

import org.fast.cms.common.enums.IsDeletedEnum;
import org.fast.cms.common.utils.CommonUtils;
import org.fast.cms.common.utils.string.StringUtils;
import org.fast.cms.domain.admin.bean.UserListBean;
import org.fast.cms.domain.admin.request.user.UserQueryBean;
import org.fast.cms.domain.admin.response.user.UserResponseBean;
import org.fast.cms.entity.admin.SysUser;
import org.fast.cms.entity.admin.SysUserExample;
import org.fast.cms.enums.BusinessTypeEnum;
import org.fast.cms.persistent.mapper.admin.SysUserMapper;
import org.fast.cms.persistent.mapper.common.SystemCommonMapper;
import org.fast.cms.service.admin.SysUserService;
import org.fast.cms.utils.UserUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.google.common.collect.Lists;

/** 
* @author weigen.ye 
* @date 创建时间：2017年6月17日 下午1:23:23 
*
*/
@Service
public class SysUserServiceImpl implements SysUserService{

	@Autowired
	private SysUserMapper userMapper;
	
	@Autowired
	private SystemCommonMapper sysComMapper; 
	
	/**
	 * 按条件查询用户
	 * @param bean
	 * @return
	 */
	@Override
	public UserResponseBean queryList(UserQueryBean bean) {
		//TODO 权限控制SQL
		bean.setDataAuthoritySql(UserUtils.getScopeSql(BusinessTypeEnum.STAFF));
		bean.setDataScope(UserUtils.getUser().getDataScope());
		if (StringUtils.isNotBlank(bean.getEndDate())) {
			bean.setEndDate(bean.getEndDate() + " 23:59:59");
		}
		PageHelper.startPage(bean.getPageNum(), bean.getPageSize());
		Page<UserListBean> list = sysComMapper.getUserList(bean);
		UserResponseBean ret = new UserResponseBean();
		CommonUtils.setPageInfo(ret, list);
		return ret;
	}
	
	@Override
	public SysUser getUserById(Integer userId) {
		if(userId==null||userId<0){
			return null;
		}
		SysUser user = userMapper.selectByPrimaryKey(userId);
		if (user == null || user.getIsDeleted().equals(IsDeletedEnum.DELETE.getKey())) {
			return null;
		}
		return user;
	}

	@Override
	public Integer[] getUserIdByName(String userName) {
		List<Integer> listUserId = Lists.newArrayList();
		SysUserExample example = new SysUserExample();
		example.createCriteria().andIsDeletedEqualTo(IsDeletedEnum.NORMAL.getKey()).andUserNameLike("%"+userName+"%");
		List<SysUser> userList = userMapper.selectByExample(example);
		for (SysUser u : userList) {
			listUserId.add(u.getUserId());
		}
	    return listUserId.toArray(new Integer[listUserId.size()]);
	}

	@Override
	public SysUser getUserByLoginName(String loginName) {
		SysUserExample example = new SysUserExample();
		example.createCriteria().andLoginNameEqualTo(loginName).andIsDeletedEqualTo(IsDeletedEnum.NORMAL.getKey());
		List<SysUser> lisUser = userMapper.selectByExample(example);
		if (lisUser.size() > 0) {
			return lisUser.get(0);
		}
		return null;
	}

}
